namespace DotNetNuke.HttpModules
{
    using DotNetNuke.Common;
    using DotNetNuke.Entities.Portals;
    using DotNetNuke.Security.Authentication;
    using System;
    using System.Web;

    public class AuthenticationModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication application)
        {
            AuthenticationController.SetStatus(Globals.GetPortalSettings().PortalId, AuthenticationStatus.Undefined);
            application.AuthenticateRequest += new EventHandler(this.OnAuthenticateRequest);
        }

        public void OnAuthenticateRequest(object s, EventArgs e)
        {
            PortalSettings _portalSettings = Globals.GetPortalSettings();
            if (Configuration.GetConfig().WindowsAuthentication)
            {
                HttpRequest Request = HttpContext.Current.Request;
                HttpResponse Response = HttpContext.Current.Response;
                bool blnWinLogon = Request.RawUrl.ToLower().IndexOf("WindowsSignin.aspx".ToLower()) > -1;
                bool blnWinLogoff = (AuthenticationController.GetStatus(_portalSettings.PortalId) == AuthenticationStatus.WinLogon) && (Request.RawUrl.ToLower().IndexOf("Logoff.aspx".ToLower()) > -1);
                if (AuthenticationController.GetStatus(_portalSettings.PortalId) == AuthenticationStatus.Undefined)
                {
                    string url;
                    AuthenticationController.SetStatus(_portalSettings.PortalId, AuthenticationStatus.WinProcess);
                    if (Request.ApplicationPath == "/")
                    {
                        url = "/Admin/Security/WindowsSignin.aspx?tabid=" + _portalSettings.ActiveTab.TabID.ToString();
                    }
                    else
                    {
                        url = Request.ApplicationPath + "/Admin/Security/WindowsSignin.aspx?tabid=" + _portalSettings.ActiveTab.TabID.ToString();
                    }
                    Response.Redirect(url);
                }
                else if ((((AuthenticationController.GetStatus(_portalSettings.PortalId) != AuthenticationStatus.WinLogoff) && blnWinLogoff) ? 1 : 0) != 0)
                {
                    new AuthenticationController().AuthenticationLogoff();
                }
                else if ((((AuthenticationController.GetStatus(_portalSettings.PortalId) == AuthenticationStatus.WinLogoff) && blnWinLogon) ? 1 : 0) != 0)
                {
                    AuthenticationController.SetStatus(_portalSettings.PortalId, AuthenticationStatus.Undefined);
                    Response.Redirect(Request.RawUrl);
                }
            }
        }

        public string ModuleName
        {
            get
            {
                return "AuthenticationModule";
            }
        }
    }
}

